package com.study.listener;

import cn.hutool.json.JSONUtil;
import com.study.cacheManager.GroupCacheManager;
import com.study.cacheManager.UserInfoCacheManager;
import com.study.dao.entity.CanalMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author canace
 * @version 1.0
 * @description Canal + RabbitMQ 监听数据库变化
 * @date 2024/1/30 13:59
 */

@Component
@Slf4j
@RequiredArgsConstructor
public class CanalListener {

    private final GroupCacheManager groupCacheManager;

    private final UserInfoCacheManager userInfoCacheManager;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "canal.queue", durable = "true"),
                    exchange = @Exchange(value = "canal.exchange"),
                    key = "canal.shortlink"
            )
    })
    public void handleDataChange(@Payload CanalMessage<?> message) {
        String tableName = message.getTable();
        if ("t_group".equals(tableName)) {
            if ("INSERT".equals(message.getType())) {
                // 新增只需要清空用户名的分组缓存即可
                String username = JSONUtil.parseObj(message.getData().get(0)).getStr("username");
                log.info("新增分组，清空用户名为{}的分组缓存", username);
                groupCacheManager.delCacheGroupListByUsername(username);
            } else {
                // 其他情况需要清空当前gid的缓存和用户名的缓存
                String username = JSONUtil.parseObj(message.getData().get(0)).getStr("username");
                String gid = JSONUtil.parseObj(message.getData().get(0)).getStr("gid");
                log.info("修改或删除分组，清空用户名为{}的分组缓存和gid为{}的分组缓存", username, gid);
                groupCacheManager.delCacheGroupByGid(gid);
                groupCacheManager.delCacheGroupListByUsername(username);
            }
        } else if ("t_user".equals(tableName)) {
            // 用户名只需要更新用户信息缓存即可
            if ("UPDATE".equals(message.getType())) {
                // 新增只需要清空用户名的分组缓存即可
                String username = JSONUtil.parseObj(message.getData().get(0)).getStr("username");
                log.info("修改用户信息，用户名为{}的用户信息缓存", username);
                userInfoCacheManager.delCacheUserInfoByUsername(username);
            }
        }
    }
}
